package com.acoreful.acf2java.commons.utils;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

public class PageBuilder {
	private static final int DEFAULT_PAGE_SIZE = 10;
	private static final int DEFAULT_PAGE = 0;

	private static int buildSize(final Integer pageSize) {
		if (pageSize == null) {
			return DEFAULT_PAGE_SIZE;
		}
		return pageSize >= 0 ? pageSize : DEFAULT_PAGE_SIZE;
	}

	private static int buildPage(final Integer pageNum) {
		if (pageNum == null) {
			return DEFAULT_PAGE;
		}
		int page = pageNum - 1;
		return page >= 0 ? page : DEFAULT_PAGE;
	}

	public static Pageable buildPageable(final Integer pageNum, final Integer pageSize) {
		return new PageRequest(buildPage(pageNum), buildSize(pageSize));
	}

	public static Pageable buildPageable(final Integer pageNum, final Integer pageSize, Sort sort) {
		if(sort==null){
			return new PageRequest(buildPage(pageNum), buildSize(pageSize));
		}
		return new PageRequest(buildPage(pageNum), buildSize(pageSize), sort);
	}
}
